package com;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Transaction;

import struct.CommentInfo;
import struct.SellerInfo;

import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;

@SuppressWarnings("serial")
public class CancelAuctionServlet extends HttpServlet 
{//client-server style (get input from client, then redirect output)
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException 
	{
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		
		
		String username = req.getParameter("username");
		String itemID = req.getParameter("itemID");
		
		System.out.println(itemID);
		
		try {
			
			for (int j = 0; j < 10; j++) {
				Transaction tx = ds.beginTransaction();
				try {
					Entity e = ds.get(KeyFactory.createKey("Auction", Integer.parseInt(itemID)));
					System.out.println("found"+e.getKey().toString()+"found");	
					ds.delete(tx, e.getKey());
					tx.commit();
					break;
					
					
				} catch (ConcurrentModificationException ed) {
					// continue
				} finally {
					if (tx.isActive())
						tx.rollback();
				}
			}
			
		} catch (EntityNotFoundException e) {
		}
		
		/*
		Query qAuctions = new Query("Auction").setKeysOnly();
		Iterable<Entity> items = ds.prepare(qAuctions).asIterable();

		for( Entity e : items){
			if(e.getKey().toString().equals(itemID)){
				System.out.println("BINGO");
				ds.delete(auction.getKey());
				break;
			}
		}
		*/
		
		
		req.setAttribute("username", username);

		req.getRequestDispatcher("sellerIndex.jsp").forward(req, resp);
	}
}